package datascope.scan;


import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * Created by TD on 2021/11/2
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}
)})
public class InterCepter implements Interceptor {

    private static final Logger log = LoggerFactory.getLogger(InterCepter.class);

    private IDataScopeProvider dataScopeProvider;

    public InterCepter(IDataScopeProvider var4) {
        if (null != var4) {
            this.dataScopeProvider = var4;
            // 初始化缓存
            Cache.O0000oo0();
        }

    }

    @Override
    public Object intercept(Invocation var1) throws Throwable {
        return sqlRender(var1, this.dataScopeProvider);
    }

    /**
     *  处理数据权限
     * @param var0
     * @param var2
     * @return
     * @throws Throwable
     */
    public static Object sqlRender(Invocation var0, IDataScopeProvider var2) throws Throwable {

        Object[] var3 = var0.getArgs();
        MappedStatement var4 = (MappedStatement) var3[0];
        SqlCommandType var5 = var4.getSqlCommandType();
        if (var5 != SqlCommandType.UNKNOWN && var5 != SqlCommandType.FLUSH) {
            if (null != var2) {
                var2.sqlRender(var3, var4, var5);
            }
            Object[] var0Args = var0.getArgs();
            System.out.println(var0Args[0]);
            //
            //MetaObject metaObject = SystemMetaObject.forObject( PluginUtils.realTarget(var0.getTarget()));
            //String originalSql = ((String) metaObject.getValue("delegate.boundSql.sql")).replaceAll("\\n", StrUtil.EMPTY).replaceAll("\\t", StrUtil.EMPTY);
            Object var6;
            var6 = var0.proceed();

            return var6;
        } else {
            return var0.proceed();
        }
    }


    @Override
    public Object plugin(Object var1) {
        return var1 instanceof Executor ? Plugin.wrap(var1, this) : var1;
    }

    @Override
    public void setProperties(Properties var1) {
    }
}
